import request from "./request";
import getUrlParameter from "@/utils/urlparameter";

import { ElMessage, ElMessageBox } from "element-plus";
import type { Action } from "element-plus";
import { useStore } from "@/stores";
/**
 * 查询阀门的开关状态
 * 0--关，1--开
 * @param id 设备ID
 * @param type 统计信息类别 1滴灌 2喷灌
 * @param callback
 */
const queryValve = (id: string, type: string, callback: Function) => {
    request.post(`/modbus-api/deviceOperate/getDoByUid?addr=${id}&type=${type}`).then((res: any) => {
        callback(res.msg);
    });
};
/**
 * 控制阀门开关
 * @param id 设备ID
 * @param status 开关状态 0关 1开 或 传value
 * @param type 统计信息类别 1滴灌 2喷灌
 */
const valve = (id: any, status: any, type: any, callback: Function) => {
    queryValve(id, type, (valveData: any) => {
        if (valveData == 0 && status == "1") {
            request.post(`/modbus-api/deviceOperate/sendControl?addr=${id}&status=${status}&type=${type}`).then((res: any) => {
                // console.log(res, "321321321");
                if (res.msg == "操作成功") {
                    console.log("阀门打开成功");
                    callback(true);
                } else {
                    ElMessageBox.alert("阀门打开失败，请稍后再试！", "提示", {
                        confirmButtonText: "确定",
                    });
                    callback(false);
                }
            });
        } else if (valveData == 1 && status == "1") {
            console.log("阀门已经打开");
            callback(true);
        }
        if (valveData == 1 && status == "0") {
            request.post(`/modbus-api/deviceOperate/sendControl?addr=${id}&status=${status}&type=${type}`).then((res: any) => {
                if (res.msg == "操作成功") {
                    console.log("阀门关闭成功");
                    callback(true);
                } else {
                    ElMessageBox.alert("阀门关闭失败，请稍后再试！", "提示", {
                        confirmButtonText: "确定",
                    });
                    callback(false);
                }
            });
        } else if (valveData == 0 && status == "0") {
            callback(true);
        }
    });
};
/**
 * 查询泵的开关状态
 * 0--关，1--开
 * @param code 机房设备编码
 */
const queryPump = (code: string, callback: Function) => {
    request.post(`/modbus-api/deviceOperate/getDiByUid?addr=${code}`).then((res: any) => {
        callback(res.msg);
    });
};
/**
 * 控制泵的开关
 * @param onOffType 开关状态 0关 1开
 * @param jfDeviceId 机房设备码
 */
const pump = (onOffType: any, callback: Function) => {
    queryPump(getUrlParameter("id"), (pumpData: any) => {
        if (onOffType == 1 && pumpData == 0) {
            request.post(`/modbus-api/deviceOperate/sendControlByDgb?status=1&jfDeviceId=${getUrlParameter("id")}`).then((res: any) => {
                if (res.msg == "操作成功") {
                    console.log("水泵打开成功");
                    callback(true);
                } else {
                    ElMessageBox.alert("水泵打开失败，请稍后再试！", "提示", {
                        confirmButtonText: "确定",
                    });
                    callback(false);
                }
            });
        } else if (onOffType == 1 && pumpData == 1) {
            callback(true);
        }
        if (onOffType == 0 && pumpData == 1) {
            request.post(`/modbus-api/deviceOperate/sendControlByDgb?status=0&jfDeviceId=${getUrlParameter("id")}`).then((res: any) => {
                if (res.msg == "操作成功") {
                    console.log("水泵关闭成功");
                    callback(true);
                } else {
                    ElMessageBox.alert("水泵关闭失败，请稍后再试！", "提示", {
                        confirmButtonText: "确定",
                    });
                    callback(false);
                }
            });
        } else if (onOffType == 0 && pumpData == 0) {
            console.log("水泵关闭成功");
            callback(true);
        }
    });
};
/**
 * 切换机房远程或本地的操作
 * 0关，1打开
 */
const getIoState = () => {
    const store = useStore();
    let data = {
        msg: store.getState,
    };
    return new Promise((resolve, reject) => {
        resolve(data);
    });
};
const longDistance = (onOffType: any, callback: Function) => {
    // 查询机房设备远程状态
    // request.post(`/modbus-api/deviceOperate/getDiByUidIo1?addr=${getUrlParameter("id")}`).then((res: any) => {
    getIoState().then((res: any) => {
        // 如果远程为关闭状态，则打开远程控制
        // console.log(res.msg);
        console.log(`设备远程状态：${res.msg == "1" ? "开" : "关"}`);
        if (onOffType == 1 && res.msg == 0) {
            request.post(`/modbus-api/deviceOperate/sendControlByQhycz?status=1&jfDeviceId=${getUrlParameter("id")}`).then((re: any) => {
                if (re.msg == "操作成功") {
                    // callback(true);
                    console.log("设备远程开启成功");
                    // 查看电源总闸状态
                    // powerLight(onOffType, (data: any) => {
                    callback(true);
                    // });
                } else {
                    ElMessageBox.alert("机房设备切换远程操作失败，请稍后再试！", "提示", {
                        confirmButtonText: "确定",
                    });
                    callback(false);
                }
            });
        } else if (onOffType == 1 && res.msg == 1) {
            // 查看电源总闸状态
            // powerLight(onOffType, (data: any) => {
            //     callback(data);
            // });
            callback(true);
        }
        if (onOffType == 0 && res.msg == 1) {
            request.post(`/modbus-api/deviceOperate/sendControlByQhycz?status=1&jfDeviceId=${getUrlParameter("id")}`).then((re: any) => {
                if (re.msg == "操作成功") {
                    // callback(true);
                    console.log("设备远程开启成功");
                    callback(true);
                } else {
                    ElMessageBox.alert("机房设备切换本地操作失败，请稍后再试！", "提示", {
                        confirmButtonText: "确定",
                    });
                    callback(false);
                }
            });
        } else if (onOffType == 0 && res.msg == 0) {
            callback(true);
        }
    });
};
/**
 * 电源总闸合闸操作
 */
const powerLight = (onOffType: any, callback: Function) => {
    request.post(`/modbus-api/deviceOperate/getDiByUidIo0?addr=${getUrlParameter("id")}`).then((res: any) => {
        console.log(`电源总闸状态：${res.msg == "1" ? "开" : "关"}`);
        // 如果没有合闸，，，则合闸，
        if (onOffType == 1 && res.msg == 0) {
            request.post(`/modbus-api/deviceOperate/sendControlByDDyzz?status=1&jfDeviceId=${getUrlParameter("id")}`).then((re: any) => {
                if (re.msg == "操作成功") {
                    console.log("电源合闸成功");
                    callback(true);
                } else {
                    ElMessageBox.alert("电源合闸失败，请稍后再试！", "提示", {
                        confirmButtonText: "确定",
                    });
                    callback(false);
                }
            });
        } else if (onOffType == 1 && res.msg == 1) {
            callback(true);
        }
        // 断电
        if (onOffType == 0 && res.msg == 1) {
            request.post(`/modbus-api/deviceOperate/sendControlByDDyzz?status=0&jfDeviceId=${getUrlParameter("id")}`).then((re: any) => {
                if (re.msg == "操作成功") {
                    console.log("电源断开成功");
                    callback(true);
                } else {
                    ElMessageBox.alert("电源断开失败，请稍后再试！", "提示", {
                        confirmButtonText: "确定",
                    });
                    callback(false);
                }
            });
        } else if (onOffType == 0 && res.msg == 0) {
            console.log("电源已断开");
            callback(true);
        }
    });
};
/**
 * 修改清肥水供应状态
 */
const alterTheState = (data: any, onOffType: any, callback: Function) => {
    // 查询供应状态
    // 1清水 2肥水
    request.post(`/modbus-api/deviceOperate/getDiByUidQsfs?addr=${getUrlParameter("id")}&type=${data.irrigationSelectionId}`).then((res: any) => {
        console.log(`${data.irrigationSelectionId == 1 ? "清水" : "肥水"}供应状态：${res.msg}`);
        if (onOffType == 1 && res.msg == 0) {
            // 切换供应状态
            request.post(`/modbus-api/deviceOperate/sendControlByqsfsgy?status=1&jfDeviceId=${getUrlParameter("id")}&type=${data.irrigationSelectionId}`).then((re: any) => {
                if (re.msg == "操作成功") {
                    console.log(`${data.irrigationSelectionId == 1 ? "清水" : "肥水"}供应设置成功`);
                    pump(onOffType, (d: any) => {
                        callback(d);
                    });
                } else {
                    ElMessageBox.alert("供应状态切换失败，请稍后再试！", "提示", {
                        confirmButtonText: "确定",
                    });
                    callback(false);
                }
            });
        } else if (onOffType == 1 && res.msg == 1) {
            pump(onOffType, (d: any) => {
                callback(d);
            });
        }
        if (onOffType == 0 && res.msg == 1) {
            // 切换供应状态
            request.post(`/modbus-api/deviceOperate/sendControlByqsfsgy?status=0&jfDeviceId=${getUrlParameter("id")}&type=${data.irrigationSelectionId}`).then((re: any) => {
                if (re.msg == "操作成功") {
                    console.log(`${data.irrigationSelectionId == 1 ? "清水" : "肥水"}供应设置成功`);
                    callback(true);
                } else {
                    ElMessageBox.alert("供应状态切换失败，请稍后再试！", "提示", {
                        confirmButtonText: "确定",
                    });
                    callback(false);
                }
            });
        } else if (onOffType == 0 && res.msg == 0) {
            callback(true);
        }
    });
};
/**
 * 设备控制器
 * @param item 要控制的设备
 * @param onOffType 控制类型  0关 1开
 * @param operationType 1滴灌 2喷灌
 * @param callback 要返回的结果
 */
const deviceControl = (itemDevice: any, onOffType: string, operationType: any, callback: Function) => {
    // 深拷贝要控制的设备
    let item = JSON.parse(JSON.stringify(itemDevice));
    // onOffType = "0";
    // console.log(item);
    // 执行打开指令
    if (onOffType == "1") {
        // 切换远程
        longDistance(onOffType, () => {
            // 电源合闸
            powerLight(onOffType, () => {
                // 修改清肥水供应状态
                alterTheState(item, onOffType, (state: any) => {
                    // console.log(state, 11);
                    // 开关阀门操作
                    if (state) {
                        valve(item.deviceId, onOffType, operationType, (handle: any) => {
                            console.log("操作成功");
                            callback(handle);
                        });
                    }
                });
            });
        });

        // 切换设备远程开关
        // longDistance(onOffType, (longDistanceState: any) => {
        //     // console.log(longDistanceState);
        //     // 电源合闸成功
        //     if (longDistanceState) {
        //         // 修改清肥水供应状态
        //         alterTheState(item, onOffType, (state: any) => {
        //             // console.log(state, 11);
        //             // 开关阀门操作
        //             if (state) {
        //                 valve(item.deviceId, onOffType, operationType, (handle: any) => {
        //                     console.log("操作成功");
        //                     callback(handle);
        //                 });
        //             }
        //         });
        //     }
        // });
    } else {
        // 执行关闭指令
        // 关闭阀门
        valve(item.deviceId, onOffType, operationType, (handle: any) => {
            // callback(handle);
            if (handle) {
                // 关闭水泵
                pump(onOffType, (p: any) => {
                    if (p) {
                        // 修改清水肥水供应状态
                        alterTheState(item, onOffType, (state: any) => {
                            if (state) {
                                // 执行断电操作
                                powerLight(onOffType, (off: any) => {
                                    if (off) {
                                        // 切换机房设备远程值
                                        longDistance(onOffType, (longRange: any) => {
                                            console.log(longRange);
                                            callback(longRange);
                                        });
                                    }
                                });
                            }
                        });
                    }
                });
            }
        });
    }
};
export default deviceControl;
